package com.smartfast4j.netty.echoclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

/**
 * 引导客户端
 */
public class EchoClient {
    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start()
        throws Exception {
        //用于处理连接的生命周期中所发生的事件
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建一个客户端引导类实例
            Bootstrap b = new Bootstrap();
            b.group(group)//指定EventLoopGroup以处理客户端事件；需要适用于NIO的实现
                .channel(NioSocketChannel.class)//适用于NIO传输的Channel类型
                .remoteAddress(new InetSocketAddress(host, port))//设置服务器的远程连接地址和端口号InetSocketAddress
                .handler(new ChannelInitializer<SocketChannel>() {
                    /**
                     * 在创建Channel时，向ChannelPipeline中添加一个EchoClientHandler实例
                     */
                    @Override
                    public void initChannel(SocketChannel ch)
                        throws Exception {
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });
            ChannelFuture f = b.connect().sync();//连接到远程服务器，阻塞等待直到连接完成
            f.channel().closeFuture().sync();//阻塞，直到Channel 关闭
        } finally {
            //关闭线程池并且释放所有的资源
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args)
            throws Exception {
        if (args.length != 2) {
            System.err.println("Usage: " + EchoClient.class.getSimpleName() +
                    " <host> <port>"
            );
            return;
        }

        final String host = args[0];
        final int port = Integer.parseInt(args[1]);
        new EchoClient(host, port).start();
    }
}

